package com.icesoft.wechat.controller;

import com.icesoft.framework.core.controller.BaseController;
import com.icesoft.framework.core.vo.JsonResult;
import com.icesoft.system.annotation.SafeRequest;
import com.icesoft.system.auth.entity.LoginUser;
import com.icesoft.wechat.applet.entity.WechatAuthorizationCode;
import com.icesoft.wechat.auth.WechatCredential;
import com.icesoft.wechat.entity.WechatUser;
import com.icesoft.wechat.service.impl.WechatLoginService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/wechat")
public class WechatAuthController extends BaseController {

	private final WechatLoginService wechatLoginService;

	@SafeRequest
	@PostMapping("/getWechatAuthorizationCode")
	public JsonResult<?> getWechatAuthorizationCode(@RequestBody WechatCredential wechatCredential) {
		try {
			WechatAuthorizationCode wechatAuthorizationCode = wechatLoginService.getWechatAuthorizationCode(wechatCredential);
			return JsonResult.OK(wechatAuthorizationCode);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@SafeRequest
	@PostMapping("/login")
	public JsonResult<?> login(@RequestBody WechatCredential wechatCredential) {
		try {
			WechatUser wechatUser = wechatLoginService.login(wechatCredential);
			return JsonResult.OK(wechatUser);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@SneakyThrows
	@SafeRequest
	@PostMapping("/refreshToken")
	public JsonResult<?> refreshToken(HttpServletRequest request, @NotNull(message = "缺失参数【loginType】") String loginType, @NotNull(message = "缺失参数【token】") String token) {
		try {
			LoginUser<WechatUser> loginUser = wechatLoginService.refreshToken(token);
			return JsonResult.OK(loginUser.getUser().getToken());
		} catch (Exception e) {
			return JsonResult.FAIL_EXCEPTION("请先登录！");
		}
	}

}
